import router from './router'
import store from './store'
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
    getStorage,
    setStorage,
    removeStorage
} from '@/utils/auth'
import {
    wxLogin
} from "@/api/home";

NProgress.configure({
    showSpinner: false
})

function getQueryString(name) { //hash模式中需要用到解析url中的参数的函数
    let arr = (location.hash || "")
        .substr(location.hash.indexOf("?") + 1)
        .replace(/^#/, "")
        .split("&");
    for (let i = 0; i < arr.length; i++) {
        let data = arr[i].split("=");
        if (data.length == 2 && data[0] == name) {
            return data[1];
        }
    }
    return null;
}

function loginUrl() {
    const appid = "wx948f6f8acc01abd1";
    const redirect_uri = encodeURIComponent(window.location.href.split("?")[0]);
    console.log(redirect_uri)
    const scope = "snsapi_userinfo";
    const urls = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
    return urls
}


const whiteList = ['/login']


router.beforeEach(async (to, from, next) => {
    /**  正式
    console.log(to)
    NProgress.start();
    let hasToken = getStorage("userToken");
    if (hasToken) {
        console.log('有token')
        next();
    } else {
        console.log('没token，有code')
        let code = getQueryString("code");
        if (code) {
            console.log('进来了')
            let res = await wxLogin(code);
            if (res.data.status == 200) {
                console.log('成功')
                store.dispatch("user/commitSaveData", res.data);
                setStorage("userInfo", JSON.stringify(res.data));
                setStorage("userToken", res.data.user.token);
                axios.defaults.headers.common['token'] = res.data.user.token;
                next()
            } else if (res.data.status == 40003 || res.data.status == 40029) {
                console.log('报错')
                removeStorage("userInfo");
                removeStorage("userToken");
                axios.defaults.headers.common['token'] = "";
                window.location.href = loginUrl();
            }
        } else {
            console.log('什么都没有')
            let href = window.location.href;
            if (href.includes("code")) {
                console.log('有code')
                let url = href.substring(0, href.length - 2);
                let codeSite = url.indexOf("?code");
                let urlLeft = url.substring(0, codeSite);
                let urlRight = url.substring(codeSite, url.length);
                window.location.href = urlLeft + "#/" + urlRight;
            } else {
                console.log('没有code')
                window.location.href = loginUrl();
            }
        }
    }
    **/
    NProgress.start()
    const hasToken = getStorage("userToken");
    const doctorToken = getStorage("doctorToken");
    if (hasToken) {
        if (to.path === '/login') {
            next('/')
            NProgress.done()
        } else {
            // store.commit('user/clearToken') // 取消请求
            next()
        }
    } else if (doctorToken) {
        if (to.path === '/login') {
            next('/')
            NProgress.done()
        } else {
            // store.commit('user/clearToken') // 取消请求
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // store.commit('user/clearToken') // 取消请求
            next()
        } else {
            next(`/login`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})